package pluginGenerator;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.JavaRuntime;

import ctxSemanticsGen.appDependent.ClassFetcher;




public class PluginClassFetcher implements ClassFetcher {
	
	
	private IJavaProject selectedProject;
	private URLClassLoader classLoader;
	
	
	
	public PluginClassFetcher(IJavaProject selectedProject){
		
		/* http://sdqweb.ipd.kit.edu/wiki/
			JDT_Tutorial:_Class_Loading_in_a_running_plugin */
		
		try {
			String[] classPathEntries = JavaRuntime
			.computeDefaultRuntimeClassPath(selectedProject);

			
			
			List<URL> urlList = new ArrayList<URL>();
			for (int i = 0; i < classPathEntries.length; i++) {
				String entry = classPathEntries[i];
				IPath path = new Path(entry);
				URL url = path.toFile().toURI().toURL();
				urlList.add(url);
			}
			ClassLoader parentClassLoader = Thread.currentThread()
			.getContextClassLoader();
			URL[] urls = (URL[]) urlList.toArray(new URL[urlList.size()]);
			classLoader = new URLClassLoader(urls, parentClassLoader);

		} catch (Exception e) { throw new RuntimeException(e.getCause()); }
	}
	

	@Override
	public Class fetchClass(String qualifiedClassName)
	                   throws ClassNotFoundException {	
		return classLoader.loadClass(qualifiedClassName);	
	}

}
